package dao

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go-admin/base/utils"
	"strings"
)

var _ GroupModel = (*customGroupModel)(nil)

type (
	// GroupModel is an interface to be customized, add more methods here,
	// and implement the added methods in customGroupModel.
	GroupModel interface {
		FindAll(ctx context.Context) ([]*Group, error)
		FindByName(ctx context.Context, name string) (*Group, error)
		FindByIds(ctx context.Context, ids []int64) ([]*Group, error)
		DeleteByIds(ctx context.Context, ids []int64) error
		groupModel
	}

	customGroupModel struct {
		*defaultGroupModel
	}
)

func (c customGroupModel) FindByIds(ctx context.Context, ids []int64) ([]*Group, error) {
	query := fmt.Sprintf("select %s from %s where `id`  in ( %s ) ", groupRows, c.table, strings.Join(utils.GeneratePlaceholderByInt64(ids), ","))
	var resp []*Group
	err := c.conn.QueryRowsCtx(ctx, &resp, query, utils.ConvertToAny(ids)...)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customGroupModel) FindByName(ctx context.Context, name string) (*Group, error) {
	query := fmt.Sprintf("select %s from %s where `name` = ? ", groupRows, c.table)
	var resp *Group
	err := c.conn.QueryRowCtx(ctx, &resp, query, name)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customGroupModel) FindAll(ctx context.Context) ([]*Group, error) {
	query := fmt.Sprintf("select %s from %s  ", groupRows, c.table)
	var resp []*Group
	err := c.conn.QueryRowsCtx(ctx, &resp, query)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customGroupModel) DeleteByIds(ctx context.Context, ids []int64) error {
	query := fmt.Sprintf("delete from %s where `id` in ( %s )", c.table, strings.Join(utils.GeneratePlaceholderByInt64(ids), ","))
	_, err := c.conn.ExecCtx(ctx, query, utils.ConvertToAny(ids)...)
	return err
}

// NewGroupModel returns a model for the database table.
func NewGroupModel(conn sqlx.SqlConn) GroupModel {
	return &customGroupModel{
		defaultGroupModel: newGroupModel(conn),
	}
}
